package com.msb.mall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.msb.common.utils.HttpUtils;
import com.msb.mall.member.entity.MemberLevelEntity;
import com.msb.mall.member.exception.PhoneExesitExecpExtion;
import com.msb.mall.member.exception.UserNameEXesitExecpExtion;
import com.msb.mall.member.service.MemberLevelService;
import com.msb.mall.member.vo.MemberLoginVO;
import com.msb.mall.member.vo.MemberReigerVO;
import com.msb.mall.member.vo.SocialUser;
import org.apache.commons.codec.digest.Md5Crypt;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.msb.common.utils.PageUtils;
import com.msb.common.utils.Query;

import com.msb.mall.member.dao.MemberDao;
import com.msb.mall.member.entity.MemberEntity;
import com.msb.mall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {


    @Autowired
    MemberLevelService memberLevelService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    /**
     *  完成会员的注册功能
     * @param vo
     */
    @Override
    public void register(MemberReigerVO vo) throws PhoneExesitExecpExtion, UserNameEXesitExecpExtion {
        MemberEntity memberEntity = new MemberEntity();


        // 设置会员等级 默认值
        MemberLevelEntity memberLevelEntity
                =memberLevelService.queryMemberLevelDefault();
        memberEntity.setLevelId(memberLevelEntity.getId());

        // 添加对应的账号和手机号是不能重复的
        checkUsernameUnique(vo.getUserName());//判断用户名是否存在
        checkPhoneUnique(vo.getPhone());//判断手机号是否存在

        memberEntity.setMobile(vo.getPhone());
        memberEntity.setUsername(vo.getUserName());

        // 需要对密码做加密处理
         BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
         String encode = bCryptPasswordEncoder.encode(vo.getPassword());
         memberEntity.setPassword(encode);
        // 设置其他的默认值
        this.save(memberEntity);


    }

    /**
     * 登入
     * @param memberLoginVO
     */
    @Override
    public MemberEntity login(MemberLoginVO memberLoginVO) {

        //根据用户传过来的手机号或者账户来查询是否存在注册过的账号
        MemberEntity mobile = this.getOne(new QueryWrapper<MemberEntity>()
                .eq("username", memberLoginVO.getUserName())
                .or()
                .eq("mobile", memberLoginVO.getPhone()));

        if (mobile != null) {
         //验证输入的密码和数据库的密码是否一致
           BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
           boolean matches = bCryptPasswordEncoder.matches(memberLoginVO.getPassword(), mobile.getPassword());
            if (matches) {
                //密码一致
                return mobile;
            }
        }

        return null;
    }

    /**
     * 社交登入
     * @param socialUser
     * @return
     */
    @Override
    public MemberEntity authLogin(SocialUser socialUser) {

        String uid = socialUser.getUid();
        MemberEntity memberEntity = this.getOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        MemberEntity Entity = new MemberEntity();
        if (memberEntity != null) {
            // 说明用户不是第一次社交登录 那么就更新相关信息 登录功能
            Entity.setId(memberEntity.getId());
            Entity.setAccessToken(socialUser.getAccessToken());
            Entity.setExpiresIn(socialUser.getExpiresIn());
            this.updateById(Entity);
            // 在返回的登录用户信息中我们同步的也保存 token和过期时间
            memberEntity.setExpiresIn(socialUser.getExpiresIn());
            memberEntity.setAccessToken(socialUser.getAccessToken());
            return memberEntity;
        }
        // 如果该用户是第一次社交登录，那么需要注册
        Entity.setAccessToken(socialUser.getAccessToken());
        Entity.setExpiresIn(socialUser.getExpiresIn());
        Entity.setSocialUid(socialUser.getUid());

        // 通过token调用微博开发的接口来获取用户的相关信息
        try {
            Map<String, String> querys = new HashMap<>();
            querys.put("access_token", socialUser.getAccessToken());
            querys.put("uid", socialUser.getUid());
            HttpResponse response = HttpUtils.doGet("https://api.weibo.com"
                    , "/2/users/show.json"
                    , "get"
                    , new HashMap<>()
                    , querys
            );
            if (response.getStatusLine().getStatusCode() == 200) {

                HttpEntity entity = response.getEntity();
               String json = EntityUtils.toString(entity);
                JSONObject jsonObject = JSON.parseObject(json);
             String screen_name = jsonObject.getString("screen_name");
                String gender = jsonObject.getString("gender");
             Entity.setGender("m".equals(gender)?1:0);
             Entity.setNickname(screen_name);
            }
        } catch (Exception ex) {
        }
        // 注册用户信息
        this.save(Entity);
        return Entity;
    }

    /**
     * 判断手机号是否存在
     * @param phone
     */
    private void checkPhoneUnique(String phone) throws PhoneExesitExecpExtion{


        int mobile = this.count(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (mobile > 0) {
        //说明手机号存在
           throw new PhoneExesitExecpExtion();
        }
    }

    /**
     * 判断用户是否存在
     * @param userName
     */
    private void checkUsernameUnique(String userName) throws UserNameEXesitExecpExtion{

        int name = this.count(new QueryWrapper<MemberEntity>().eq("username", userName));
        if (name > 0) {
            //说明用户存在
            throw new UserNameEXesitExecpExtion();

        }


    }

}